package com.netty;

import com.github.luben.zstd.Zstd;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;

public class ZstdServer {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("Server started, waiting for connection...");
        Socket socket = serverSocket.accept();
        System.out.println("Client connected");

        InputStream in = socket.getInputStream();

        // 先读4字节的压缩数据长度 先读大端
        byte[] sizeBytes = readExactly(in, 4);
        int compressedSize = ByteBuffer.wrap(sizeBytes).getInt(); // 大端
        System.out.println("Compressed size: " + compressedSize);

        if (compressedSize <= 0 || compressedSize > 20 * 1024 * 1024) {
            throw new RuntimeException("Invalid compressed size");
        }

        // 读取压缩数据
        byte[] compressed = readExactly(in, compressedSize);

        // 解压大小估算
        long decompressedSize = Zstd.decompressedSize(compressed);
        if (decompressedSize == 0) {
            System.out.println("Unknown decompressed size, fallback to 1MB");
            decompressedSize = 1024 * 1024;
        }

        byte[] decompressed = new byte[(int) decompressedSize];
        long size = Zstd.decompress(decompressed, compressed);
        if (Zstd.isError(size)) {
            throw new RuntimeException("Decompression failed: " + Zstd.getErrorName(size));
        }

        String result = new String(decompressed, 0, (int) size, "UTF-8");
        System.out.println("Decompressed message:\n" + result);

        socket.close();
        serverSocket.close();


    }

    private static byte[] readExactly(InputStream in, int length) throws Exception {
        byte[] buffer = new byte[length];
        int read = 0;
        while (read < length) {
            int r = in.read(buffer, read, length - read);
            if (r == -1) throw new Exception("Stream closed before reading enough data");
            read += r;
        }
        return buffer;
    }

}
